<template>
  <div class="table-box">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="单据编号" prop="transactionNo">
        <el-input v-model="searchForm.transactionNo" placeholder="请输入单据编号" clearable />
      </el-form-item>
      <el-form-item label="操作类型" prop="type">
        <el-select v-model="searchForm.type" placeholder="请选择类型" clearable style="width: 180px">
          <el-option label="入库" value="IN" />
          <el-option label="出库" value="OUT" />
          <el-option label="调拨" value="TRANSFER" />
          <el-option label="盘点" value="INVENTORY" />
        </el-select>
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="searchForm.materialName" placeholder="请输入物料名称" clearable />
      </el-form-item>
      <el-form-item label="操作时间" prop="dateRange">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <el-button type="primary" :icon="CirclePlus" @click="handleInbound">入库</el-button>
      <el-button type="warning" :icon="Minus" @click="handleOutbound">出库</el-button>
      <el-button type="info" :icon="Switch" @click="handleTransfer">调拨</el-button>
      <el-button type="success" :icon="Download" @click="handleExport">导出</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading" border>
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="transactionNo" label="单据编号" />
      <el-table-column prop="type" label="操作类型">
        <template #default="scope">
          <el-tag :type="getTypeTagType(scope.row.type)">{{ getTypeText(scope.row.type) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="materialCode" label="物料编码" />
      <el-table-column prop="materialName" label="物料名称" />
      <el-table-column prop="specification" label="规格型号" />
      <el-table-column prop="unit" label="单位" />
      <el-table-column prop="quantity" label="数量" align="right">
        <template #default="scope">
          <span :class="getQuantityClass(scope.row.type)">
            {{ scope.row.type === 'OUT' ? '-' : '+' }}{{ scope.row.quantity }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="unitPrice" label="单价" align="right">
        <template #default="scope">
          ¥{{ scope.row.unitPrice }}
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="总金额" align="right">
        <template #default="scope">
          <span class="total-amount">¥{{ (scope.row.quantity * scope.row.unitPrice).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="warehouse" label="仓库" />
      <el-table-column prop="operator" label="操作人" />
      <el-table-column prop="operateTime" label="操作时间" />
      <el-table-column prop="remark" label="备注" show-overflow-tooltip />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleView(scope.row)">查看详情</el-button>
          <el-button type="danger" link @click="handleCancel(scope.row)" v-if="scope.row.status === 'PENDING'">
            撤销
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
  </div>
</template>

<script setup lang="ts" name="inventoryTransaction">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, Download, Minus, Switch } from "@element-plus/icons-vue";

const loading = ref(false);
const tableData = ref([]);
const searchFormRef = ref<FormInstance>();

// 查询表单
const searchForm = reactive({
  transactionNo: "",
  type: "",
  materialName: "",
  dateRange: []
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    IN: "success",
    OUT: "warning",
    TRANSFER: "info",
    INVENTORY: "primary"
  };
  return typeMap[type] || "info";
};

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    IN: "入库",
    OUT: "出库",
    TRANSFER: "调拨",
    INVENTORY: "盘点"
  };
  return typeMap[type] || type;
};

// 获取数量样式
const getQuantityClass = (type: string) => {
  return type === 'OUT' ? 'quantity-out' : 'quantity-in';
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData = [
      {
        id: 1,
        transactionNo: "IN202401150001",
        type: "IN",
        materialCode: "RM001",
        materialName: "钢材A",
        specification: "Q235 10*20mm",
        unit: "kg",
        quantity: 500,
        unitPrice: 8.50,
        warehouse: "原料仓",
        operator: "张三",
        operateTime: "2024-01-15 10:30:00",
        remark: "采购入库",
        status: "COMPLETED"
      },
      {
        id: 2,
        transactionNo: "OUT202401150002",
        type: "OUT",
        materialCode: "FP001",
        materialName: "智能手机X1",
        specification: "6.1寸 128GB",
        unit: "台",
        quantity: 20,
        unitPrice: 2999.00,
        warehouse: "成品仓",
        operator: "李四",
        operateTime: "2024-01-15 14:15:00",
        remark: "销售出库",
        status: "COMPLETED"
      },
      {
        id: 3,
        transactionNo: "TR202401150003",
        type: "TRANSFER",
        materialCode: "RM002",
        materialName: "塑料颗粒B",
        specification: "PP 白色",
        unit: "kg",
        quantity: 100,
        unitPrice: 12.00,
        warehouse: "原料仓 → 生产车间",
        operator: "王五",
        operateTime: "2024-01-15 16:20:00",
        remark: "生产领料",
        status: "PENDING"
      }
    ];
    
    tableData.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    console.error("获取库存事务记录失败:", error);
    ElMessage.error("获取库存事务记录失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 入库
const handleInbound = () => {
  ElMessage.info("入库功能开发中");
};

// 出库
const handleOutbound = () => {
  ElMessage.info("出库功能开发中");
};

// 调拨
const handleTransfer = () => {
  ElMessage.info("调拨功能开发中");
};

// 导出
const handleExport = () => {
  ElMessage.info("导出功能开发中");
};

// 查看详情
const handleView = (row: any) => {
  ElMessage.info(`查看单据 ${row.transactionNo} 详情`);
};

// 撤销
const handleCancel = async (row: any) => {
  ElMessageBox.confirm(`确认撤销单据 "${row.transactionNo}" 吗？`, "撤销确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        ElMessage.success("单据撤销成功");
        getTableData();
      } catch (error) {
        console.error("单据撤销失败:", error);
        ElMessage.error("单据撤销失败");
      }
    })
    .catch(() => {
      // 取消撤销
    });
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
});
</script>

<style scoped>
.search-form {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

.quantity-in {
  color: #67c23a;
  font-weight: bold;
}

.quantity-out {
  color: #f56c6c;
  font-weight: bold;
}

.total-amount {
  color: #409eff;
  font-weight: bold;
}
</style>